package com.chain.BrotherExchange.data;

import android.content.Context;
import android.support.annotation.NonNull;

import com.chain.BrotherExchange.event.LogoutEvent;
import com.chain.BrotherExchange.ui.activity.LoginActivity;
import com.chain.BrotherExchange.utils.Androids;
import com.example.common.widget.state.NetworkStateView;

import org.greenrobot.eventbus.EventBus;

/**
 * 结合viewModel 与View通信
 *
 * @param <T>
 */
public class Resource<T> {
    public T source;
    public Status state;
    public String message;

    private Resource(T source, String message, Status state) {
        this.source = source;
        this.message = message;
        this.state = state;
    }

    public static <T> Resource<T> loading() {
        return new Resource<T>(null, null, Status.LOADING);
    }

    public static <T> Resource<T> empty() {
        return new Resource<T>(null, null, Status.EMPTY);
    }

    public static <T> Resource<T> success(@NonNull T data) {
        return new Resource<>(data, null, Status.SUCCESS);
    }

    public static <T> Resource<T> success(@NonNull T data, String message) {
        return new Resource<>(data, message, Status.SUCCESS);
    }

    public static <T> Resource<T> success(String message) {
        return new Resource<>(null, message, Status.SUCCESS);
    }

    public static <T> Resource<T> error(@NonNull String message) {
        return new Resource<T>(null, message, Status.ERROR);
    }

    public static <T> Resource<T> notNetwork() {
        return new Resource<T>(null, null, Status.NOT_NETWORK);
    }

    public static <T> Resource<T> tokenError(@NonNull String message) {
        return new Resource<T>(null, message, Status.TOKEN_ERROR);
    }

    public static <T> void load(
            Context context, Resource<T> resource, NetworkStateView networkStateView, DataSource.DataCallback<T> callback) {

        if (resource != null) {
            switch (resource.state) {
                case EMPTY:
                    networkStateView.emptyNetwork();
                    break;

                case LOADING:
                    networkStateView.loadingNetwork();
                    break;

                case NOT_NETWORK:
                    networkStateView.notNetwork();
                    break;

                case ERROR:
                    networkStateView.errorNetwork(resource.message);
                    break;

                case SUCCESS:
                    callback.onResult(resource.source);
                    networkStateView.successNetwork();
                    break;

                case TOKEN_ERROR:
                    EventBus.getDefault().post(new LogoutEvent());
                    Androids.LocalConfig.logout();
                    LoginActivity.launch(context);
                    break;
            }
        }


    }

    public enum Status {SUCCESS, ERROR, LOADING, EMPTY, TOKEN_ERROR, NOT_NETWORK}
}
